package com.ks.controller;

import com.ks.base.BaseAction;
import com.ks.entity.*;
import com.ks.service.*;
import com.ks.util.HtmlUtil;
import com.ks.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.*;

/**
 * 系统级controller
 */
@Controller
@RequestMapping("/person")
public class RoleMngController extends BaseAction {

    private final static Logger log = Logger.getLogger(RoleMngController.class);

    // Servrice start
    @Autowired(required = false)
    // 自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
    private UserService<User> userService;
    @Autowired
    private UnitService unitService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ProfessionService professionService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private ExamineeService examineeService;
    @Autowired
    private RankService rankService;


    /**
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/pagedata")
    public ModelAndView pagedata(HttpServletRequest request) throws Exception {
        String id = request.getParameter("id");

        Map<String, Object> context = getRootMap();
        if (StringUtils.isNotBlank(id)) {
            context.put("label", "edit");

        }
        User user = userService.queryById(id);
        if (null != user) {
            UserRole userRole = (UserRole) userRoleService.queryByUserId(user.getId());
            if (null != userRole) {
                context.put("role_id", userRole.getRole_id());
            }
        }

        context.put("user", user);
        // 单位
        List<Unit> unitList = unitService.queryList(null);
        context.put("unit", unitList);
        // 角色
        List<Role> roleList = roleService.queryList(null);
        context.put("role", roleList);
        if(user!=null){
            UserRole userRole =(UserRole) userRoleService.queryByUserId(user.getId());
            context.put("roleId", userRole.getRole_id());
            List<Rank> ranks = rankService.findByProId(user.getPro_id());
            context.put("ranks", ranks);
        }
        // 专业
        List<Profession> professionList = professionService.queryByList(null);
        context.put("pro", professionList);

        return forword("pages/roleMng/addUser", context);
    }

    @RequestMapping("/dataList")
    public void datalist(HttpServletResponse response) throws Exception {
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        List<User> userList = userService.findAll(null);
        User user = userService.queryById(1);
        List<User> list = new ArrayList<>();
        list.add(user);
        for (User userx : userList) {
            list.add(userx);
        }
        Map<String, Object> dataMap = null;

        for (User usr : list) {
            dataMap = new HashMap<String, Object>();
            dataMap.put("id", usr.getId());
            dataMap.put("identifier", usr.getIdentifier());
            dataMap.put("name", usr.getName());
            // 单位
            Unit unit = (Unit) unitService.queryById(usr.getUnit_id());
            if (null != unit) {
                dataMap.put("unit", unit.getName());
            }
            // 角色
            List<Role> roleList = roleService.queryListByUserId(usr.getId());
            String roleStr = "";
            for (Role role : roleList) {
                roleStr = roleStr + role.getName() + ";";
            }
            dataMap.put("role", roleStr);
            // 账号
            dataMap.put("account", usr.getAccount());
            dataList.add(dataMap);
        }

        HtmlUtil.writerJson(response, dataList);
    }

    /**
     * 添加或修改数据
     *
     * @param entity
     * @param typeIds
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @RequestMapping("/save")
    @ResponseBody
    @Transactional
    public Map<String, Object> save(User entity, Integer[] typeIds, HttpServletRequest request,
                                    HttpServletResponse response) throws Exception {
        String role = request.getParameter("role");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Integer status = 1;
        String msg = "保存成功！";
        if (entity.getId() == null || StringUtils.isBlank(entity.getId().toString())) {
            String password = StringUtil.MD5("123456");
            entity.setPassword(password);
            entity.setCreatetime(new Date());
            // 判断账号是否存在
            User user = userService.queryByAccount(entity.getAccount());
            if (null != user) {
                status = 0;
                msg = "系统中已存在该账号";
            } else {
                userService.add(entity);
                // 保存用户和角色关联关系
                ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
                UserRole userRole = (UserRole) ac.getBean("userRole");
                userRole.setRole_id(Integer.parseInt(role));
                userRole.setUser_id(entity.getId());
                userRoleService.add(userRole);
            }
        } else {
            // 先删除user_role关联关系
            userRoleService.deleteByUserId(entity.getId());
            // 保存用户和角色关联关系
            ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
            UserRole userRole = (UserRole) ac.getBean("userRole");
            userRole.setRole_id(Integer.parseInt(role));
            userRole.setUser_id(entity.getId());
            userRoleService.add(userRole);
            entity.setUpdatetime(new Date());
            userService.updateBySelective(entity);
        }
        resultMap.put("status", status);
        resultMap.put("msg", msg);
        return resultMap;
    }


    @RequestMapping("/update")
    @ResponseBody
    public Map<String, Object> update(User entity, Integer[] typeIds, HttpServletRequest request,
                                    HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("userInfo");
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("msg", "操作成功");
        String yuanpass = request.getParameter("yuanpass");
        String newpass = request.getParameter("newpass");
        String confirmpass = request.getParameter("confirmpass");
        String flag = request.getParameter("flag");
        user.setPassword(StringUtil.MD5(yuanpass));
        List<User> list = userService.queryList(user);
        if ("password".equals(flag)) {
            if (list.size()>0) {
                if (newpass.equals(confirmpass)) {
                    if (StringUtils.isNotBlank(newpass)) {
                        user.setPassword(StringUtil.MD5(newpass));
                        userService.update(user);
                    } else {
                        resultMap.put("msg", "密码不能为空");
                    }
                } else {
                    resultMap.put("msg", "两次输入的密码不一致");
                }
            } else {
                resultMap.put("msg", "原密码不正确");
            }
        } else {
            userService.update(user);
        }
        return resultMap;
    }

    @RequestMapping("/getId")
    public void getId(String id, HttpServletResponse response) throws Exception {

        HtmlUtil.writerJson(response, "");
    }

    @RequestMapping("/del")
    public void delete(User entity, HttpServletResponse response) throws Exception {

        userService.del(entity);

        sendSuccessMessage(response, "删除成功");
    }

    @RequestMapping("findByUserId")
    @ResponseBody
    public Boolean findByUserId(HttpServletRequest request){
        String userId = request.getParameter("userId");
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        List<Examinee> examinees = examineeService.findByUserId(map);
        if(examinees.isEmpty()){
            return true;
        }else {
            return false;
        }
    }

    @RequestMapping("resetpass")
    @ResponseBody
    public void resetpass(String id){
        String password = StringUtil.MD5("123456");
        Map<String,Object> map = new HashMap<>();
        User user = new User();
        user.setId(Integer.parseInt(id));
        user.setPassword(password);
        userService.updateBySelective(user);
    }

    @RequestMapping("selectAjax")
    @ResponseBody
    public Map<String,Object> selectAjax(){
        Map<String,Object> map = new HashMap<>();
        map.put("units",unitService.queryList(null));
        map.put("ranks",rankService.queryList(null));
        map.put("pros",professionService.queryList(null));
        return map;
    }

    @RequestMapping("searchAjax")
    @ResponseBody
    public List<Map<String,Object>> searchAjax(String unitIds,String proIds,String rankIds){
        return userService.searchAjax(unitIds,proIds,rankIds);
    }


}
